package com.lanchetech.user.service.impl;


import com.aliyun.oss.OSSClient;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.vo.TokenHolder;
import com.lanchetech.common.util.ConnUtil;
import com.lanchetech.common.util.ThreadContext;
import com.lanchetech.service.OSSClientUtil;
import com.lanchetech.user.service.BaiduService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class BaiduServiceImpl implements BaiduService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${baidu.appKey}")
    private String appKey;

    @Value("${baidu.secretKey}")
    private String secretKey;

    @Value("${oss.bucket}")
    private String bucket;
    @Value("${oss.bucketName}")
    private String bucketName;
    @Value("${oss.http}")
    private String ossHttp;

    @Autowired
    OSSClientUtil ossClientUtil;


    // 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，
    // 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美
    private final int per = 0;
    // 语速，取值0-15，默认为5中语速
    private final int spd = 5;
    // 音调，取值0-15，默认为5中语调
    private final int pit = 5;
    // 音量，取值0-9，默认为5中音量
    private final int vol = 5;

    // 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav
    private final int aue = 6;

    public final String url = "https://tsn.baidu.com/text2audio"; // 可以使用https

    private String cuid = "1234567JAVA";

    @Override
    public String createAudio(String content) throws Exception {
        TokenHolder holder = new TokenHolder(appKey, secretKey, TokenHolder.ASR_SCOPE);
        holder.refresh();
        String token = holder.getToken();

        // 此处2次urlencode， 确保特殊字符被正确编码
        String params = "tex=" + ConnUtil.urlEncode(ConnUtil.urlEncode(content));
        params += "&per=" + per;
        params += "&spd=" + spd;
        params += "&pit=" + pit;
        params += "&vol=" + vol;
        params += "&cuid=" + cuid;
        params += "&tok=" + token;
        params += "&aue=" + aue;
        params += "&lan=zh&ctp=1";

        String substring = "." + getFormat(aue);
        // 为了避免被人遍历读取图片，图片的命名必须无规则
        String name = ThreadContext.generateRequestUUID() + substring;
        // 文件按日分目录保存
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String folder = dateFormat.format(new Date()) + "/";

        HttpURLConnection conn = (HttpURLConnection) new URL(url + "?" + params).openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setConnectTimeout(5000);
        PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
        printWriter.write(params);
        printWriter.close();
        String contentType = conn.getContentType();
        if (contentType.contains("audio/")) {
            byte[] bytes = ConnUtil.getResponseBytes(conn);
            ossClientUtil.uploadFile2OSS(new ByteArrayInputStream(bytes), name, folder);
        }
        return ossHttp + bucket + "/" + folder + name;
    }


    public static InputStream getAudioStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取音频出现异常，音频路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }

    // 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav
    private String getFormat(int aue) {
        String[] formats = {"mp3", "pcm", "pcm", "wav"};
        return formats[aue - 3];
    }
}